<template>
  <div class="app-container" style="margin-top: -25px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-show="isShow"
        >选择物料</el-button>
      </el-col>
    </el-row>
    <el-table  v-loading="loading" :summary-method="getSummaries" show-summary :data="purchaseInfoAddList" @selection-change="handleSelectionChange" row-key="columnId" :max-height="tableHeight">
      <el-table-column label="物料编号" align="center" prop="itemId" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="spec" />
      <el-table-column label="单位" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jc_iteminfo_unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="供应商编码" align="center" prop="supplyId" />-->
      <el-table-column label="供应商名称" align="center" prop="supplyName" />
      <!-- <el-table-column label="生产周期" align="center" prop="scDate">
         <template slot-scope="scope">
           <div style="display:flex">
             <el-input  clearable style="display:inline"v-model="scope.row.scDate"></el-input>
           </div>
         </template>
       </el-table-column>-->
      <el-table-column label="临时采购数量" align="center" prop="yhNum" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input  clearable style="display:inline"v-model="scope.row.yhNum"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="计划单价"  align="center" prop="jhUnitPrice" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input style="width: 100%"  controls-position="right" clearable v-model="scope.row.jhUnitPrice"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="计划金额"  align="center" prop="jhTotalPrice">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.jhUnitPrice*scope.row.yhNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="税率"  align="center" prop="taxRate">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%"  controls-position="right" clearable v-model="scope.row.taxRate"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="含税采购单价"  align="center" prop="inclusivePurchasePrice" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.inclusivePurchasePrice"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="含税采购总价"  align="center" prop="inclusivePurchaseAmount">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.inclusivePurchasePrice*scope.row.yhNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="不含税采购单价"  align="center" prop="exclusivePurchasePrice" >
        <template slot-scope="scope">
          <div style="display:flex">
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.exclusivePurchasePrice"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="不含税采购总价"  align="center" prop="exclusivePurchaseAmount">
        <template slot-scope="scope">
          <div>
            <span style="text-align: center">{{scope.row.exclusivePurchasePrice*scope.row.yhNum | numFilter}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="包装费用"  align="center" prop="packagingCost">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.packagingCost"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="运输费用"  align="center" prop="shippingCost">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.shippingCost"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="物流费用"  align="center" prop="logisticsCost">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.logisticsCost"></el-input>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="托管属性"  align="center" prop="isTuoguan">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.isTuoguan"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="材质"  align="center" prop="material">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.material"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="包装尺寸"  align="center" prop="packagingSize">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.packagingSize"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="包装材质"  align="center" prop="packagingMaterial">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.packagingMaterial"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="单箱重量"  align="center" prop="singleBoxWeight">
        <template slot-scope="scope">
          <div>
            <el-input style="width: 100%;"  controls-position="right"  clearable v-model="scope.row.singleBoxWeight"></el-input>
          </div>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index,scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--选择物料-->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" style="margin-top: -20px"  :model="form" :rules="rules" label-width="80px">
        <IteminfoSelect ref="iteminfoSelect"></IteminfoSelect>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">选 择</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addCaigoItemInfo} from "@/api/business/purchaseInfo";
import IteminfoSelect from './iteminfoSelect';

export default {
  components: {
    IteminfoSelect
  },
  name: "PurchaseInfoAdd",
  dicts: ['jc_iteminfo_unit'],
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      itemIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      isShow:false,
      // 采购详情表格数据
      purchaseInfoAddList: [],
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      supplyId:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caigouDanhao: null,
        itemName: null,
        itemId: null,
        supplyName: null,
        classId: null,
        className: null,
        caigouDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  mounted () {

  },
  created() {
   /* this.getList();*/
  },
  filters: {
    numFilter (value) {
      // 截取当前数据到小数点后两位
      let realVal = parseFloat(value).toFixed(2)
      return realVal
    }
  },
  methods: {
    /** 查询采购详情列表 */
    getList() {
      this.loading = true;
    /*  listCaigouDetail(this.queryParams).then(response => {
        this.purchaseInfoAddList = response.rows;
        this.total = response.total;
        this.loading = false;
      });*/
    },
    getCgInfoList(danhao){
      this.queryParams.caigouDanhao=danhao;
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        caigouDanhao: null,
        itemName: null,
        itemId: null,
        supplyId: null,
        supplyName: null,
        classId: null,
        className: null,
        caigouNum: null,
        unitPrice: null,
        totalPrice: null,
        caigouDate: null,
        unit: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if (index === 1 || index === 2 || index === 3 || index === 4 || index === 5 || index === 7 || index === 9) {
          return '';
        }
        for(var i=0 ;i<data.length;i++){
          data[i].totalPrice =data[i].yhNum*data[i].unitPrice;
          data[i].jhTotalPrice =data[i].yhNum*data[i].jhUnitPrice;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if(index==4){
                return prev + curr
              }else{
                return this.keepTwoDecimalFull(Number(prev) + curr);
              }
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    keepTwoDecimalFull(num) {
      var result = parseFloat(num);
      if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
      }
      result = Math.round(num * 100) / 100;
      var s_x = result.toString(); //将数字转换为字符串

      var pos_decimal = s_x.indexOf('.'); //小数点的索引值


      // 当整数时，pos_decimal=-1 自动补0
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
      }

      // 当数字的长度< 小数点索引+2时，补0
      while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
      }
      return s_x;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /*重置列表*/
    purchaseInfoAddListReset(){
      this.isShow=true;
      this.purchaseInfoAddList =[];
      this.loading = false;
    },
    /*修改*/
    purchaseInfoEditListReset(data){
      this.row = {
        factoryName: null,
        factoryCode: null,
        danhao: null,
        yhDanhao: null,
        asnDanhao: null,
        classId: null,
        className: null,
        itemName: null,
        itemId: null,
        itemCode: null,
        spec: null,
        unit: null,
        txm: null,
        supplyId: null,
        supplyName: null,
        makerCode: null,
        makerName: null,
        contractCode: null,
        contractNum: null,
        contractShare: null,
        totalPrice: null,
        unitPrice: null,
        isTuoguan: null,
        yhNum: null,
        shNum: null,
        rkNum: null,
        hgNum: null,
        thNum: null,
        yhType: null,
        yhCompany: null,
        wlCompany: null,
        dhCompany: null,
        yhTime: new Date(),
        dhStock: null,
        shName: null,
        shKuwei: null,
        shAddress: null,
        ghCompany: null,
        ghDate: null,
        ghAddress: null,
        scDate: null,
        gysYsjl: null,
        gysYssj: null,
        yddNum: null,
        ywcNum: null,
        yghwcbl: null,
        dxrl: null,
        ncgPlanId: null,
        ncgPlanNum: null,
        jcgPlanId: null,
        jcgPlanNum: null,
        ycgPlanId: null,
        ycgPlanNum: null,
        lscgPlanId: null,
        lscgPlanNum: null,
        size: null,
        singleWeight: null,
        totalWeight: null,
        rukuDate: null,
        upLine: null,
        downLine: null,
        stockSafe: null,
        useState: null,
        color: null,
        figure: null,
        caizhi: null,
        isDaizhi: null,
        packingNum: null,
        packingSize: null,
        packingCaizhi: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.isShow=false;
      this.purchaseInfoAddList =[];
      this.purchaseInfoAddList.push(data);
      this.loading = false;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "选择物料信息";
      this.itemIds=[];
      if(this.purchaseInfoAddList.length>0){
        this.purchaseInfoAddList.map((item) => {
          this.itemIds.push(item.itemCode);
        })
      }
      setTimeout(() => {
        this.$refs.iteminfoSelect.getItemInfoList(this.supplyId);
      }, 5);

    },
    /** 提交按钮 */
    submitForm() {
      const id =this.$refs.iteminfoSelect.ids;
      addCaigoItemInfo(id).then(response => {
        response.data.map((item)=>{
          item.inclusivePurchasePrice = 0;
          item.exclusivePurchasePrice = 0;
          this.purchaseInfoAddList.push(item)
        })
      });
      this.open = false;
    },
    /** 删除按钮操作 */
    handleDelete(index,row) {
      this.purchaseInfoAddList.splice(index,1);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/caigouDetail/export', {
        ...this.queryParams
      }, `采购单导出_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  ::v-deep .el-input-number.is-controls-right .el-input-number__increase{
    display: none;
    visibility: hidden;
    width: 10px !important;
    position: fixed;
    top:0;
  }
  ::v-deep .el-input-number.is-controls-right .el-input-number__decrease{
    display: none;
    visibility: hidden;
    position: fixed;
    top:0;
  }
  ::v-deep .el-table .cell{
    /*display: none;*/
    padding-right: 0;
    padding-left: -30px;
  }
</style>
